package com.lanou.zakerproject.base;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.toolbox.ImageLoader;

/**
 * Created by dllo on 16/1/18.
 */
public class MemoryCache implements ImageLoader.ImageCache {
    //先获取本地最大内存  然后除以4   即我们要的maxsize
    //判断内存还够不够，LruCache已经自带
    private LruCache<String, Bitmap> cache;//最大内存

    //初始化cache
    public MemoryCache() {
        initMemoryChche();
    }

    private void initMemoryChche() {
        int maxMemory = (int) (Runtime.getRuntime().maxMemory());
        int cacheSize = maxMemory / 4;
        cache = new LruCache<String, Bitmap>(cacheSize) {
            //重新定义size
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight() / 1024;//返回字节数除1024
            }
        };
    }

    @Override
    public Bitmap getBitmap(String url) {//通过url把图片从容器里拿出来
        return cache.get(url);//如果路径，要字符串截取
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {//通过url把图片放容器里
        cache.put(url, bitmap);
    }
}